package com.fmatos.amazingwallpapers.image.database.orm.repository;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import org.joda.time.DateTime;

import android.util.Log;

import com.fmatos.amazingwallpapers.image.database.orm.DatabaseHelper;
import com.fmatos.amazingwallpapers.image.database.orm.Photo;
import com.j256.ormlite.dao.Dao;

public class PhotoRepo {

	private static final String TAG = PhotoRepo.class.getSimpleName();
	
	private Dao<Photo, String> photoDao;
	
	
	@Inject
	public PhotoRepo(DatabaseHelper databaseHelper) {
		photoDao = databaseHelper.getPhotoDao();
	}
	
	/**
	 * Method that returns a list of all photos in the database. It is guaranteed to never return null;
	 * @return returns a list of photos. under errors or exceptions it will return an empty list
	 */
	public List<Photo> getPhotos() {
		try {
			return photoDao.queryForAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return new LinkedList<Photo>(); // let's avoid a lot of null pointer errors
	}

	public void update(Photo image) {
		try {
			photoDao.update(image);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void create(Photo image) {
		Log.i(TAG,"create photo " + image.getCaption());
		
		try {
			// TODO check if image has date, if not create a NOW
			if (image.getDate() == 0) {
				image.setDate(new DateTime().getMillis());
			}
			
			Photo newPhoto = photoDao.createIfNotExists(image);
			Log.i(TAG,"new photo " + newPhoto.getCaption());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * Guaranteed to never return null
	 * @param albumName
	 * @return
	 */
	public List<Photo> getPhotosFromAlbum(String albumName) {

		try {
			List<Photo> list = photoDao.queryForEq("albumName", albumName);
			if ( list != null ) {
				return list;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new LinkedList<Photo>();
	}

	public Photo getPhoto(String url) {
		
		try {
			return photoDao.queryForId(url);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
